<?php
class FilterController extends Zend_Controller_Action
{
	
	protected $_acl;
	protected $_userGroup;
	
	public function init()
	{
		$auth = Zend_Auth::getInstance();
		$userInfo = $auth->getStorage()->read();
		$groupBase = new GroupBase();
		if ($userInfo) {
			$userGroups = $groupBase->getUserGroup($userInfo->name);
		}
		$this->_userGroup = $userGroups[0]['name'] ? $userGroups[0]['name'] : "Users";
		$this->_acl = new Acl_PPMIS();
		$this->view->acl = $this->_acl;
		$this->view->userGroup = $this->_userGroup;
	}
	
	public function preDispatch()
	{
		$auth = Zend_Auth::getInstance();
		if($auth->getIdentity()) {
			$this->view->auth = "success";
			$userInfo = $auth->getStorage()->read();
			$this->view->userInfo = $userInfo;
		}
		$Configuration = new Configuration();
		$configurationData = $Configuration->getConfigurationInfo();
		$this->view->configuration = $configurationData;
		//$this->view->auth = 'Success';
	}
	
	public function viewAction()
	{
		$Zend_Auth = new Zend_Session_Namespace('Zend_Auth');
		$auth = Zend_Auth::getInstance();
		$userInfo = $auth->getStorage()->read();
		$id = $this->_getParam('id');
		$issue = new Issue();
		$searchRequest = new SearchRequest();
		if ($id) {
			$filterData = $searchRequest->getAdapter()->fetchRow($searchRequest->select()->where('id=?',$id));
			// saving filter xml in session for future use.
			
			$Zend_Auth->filterXml = $filterData['reqcontent'];
			$params = $this->_processXml($filterData['reqcontent']);
			$this->view->filterData = $filterData;
			$this->view->id = $id;
		
		} elseif ($projectId = $this->_getParam('projectId')) {
			$params['projects'] = array($projectId);
			if ($this->_getParam('reporterSelect') == 'issue_current_user') {
				$params['reporter'] = "specify";
				$params['reporterName'] = $userInfo->fullname;
			}
			
			if ($this->_getParam('assigneeSelect') == 'issue_current_user') {
				$params['assignee'] = "specify";
				$params['assigneeName'] = $userInfo->fullname;
			}
			
			if($this->_getParam('created') == '-1w') {
				$date = new Zend_Date();
				$date->sub(1, Zend_Date::WEEK);
				$weekAgo = $date->get();
				$params['createdAfter'] = date("Y-m-d",$weekAgo);
			}
			
			if($this->_getParam('updated') == '-1w') {
				$date = new Zend_Date();
				$date->sub(1, Zend_Date::WEEK);
				$weekAgo = $date->get();
				$params['updatedAfter'] = date("Y-m-d",$weekAgo);
			}
			
			if ($this->_getParam('resolved') == '-1w') {
				$params['resolvedAfter'] = '-1w'; 
			}
			
			if ($this->_getParam('fixfor') == -1) {
				$params['fixfor'] = '-1w'; 
			}
			
			//$Zend_Auth->filterXml = $this->_generateXml(params);
		} elseif($Zend_Auth->filterXml) {
			$params = $this->_processXml($Zend_Auth->filterXml);
		}
		$where = $this->_buildWhere($params);
		$field = $this->_getField($this->_getParam('field',1));
		$direction = $this->_getParam('direction', "DESC");
		if ($direction == "ASC") {
			$order = "DESC";
			$orderImg = 'up.gif';
		} else {
			$order = "ASC";
			$orderImg = 'down.gif';
		}
		$issuesData = $issue->getIssues($where, $field, $direction);
		
		$pageNumber = $this->_getParam('page',1);
		$offset = $this->_getParam('itemsPerPage',10);
		$paginator = Zend_Paginator::factory($issuesData);
		$paginator->setItemCountPerPage($offset);
		$paginator->setCurrentPageNumber($pageNumber);
		//Zend_Debug::dump($paginator->getPages());
		
		$this->view->issuesData = $paginator;
		$this->view->field = $field;
		$this->view->direction = $direction;
		$this->view->orderImg = $orderImg;
		$this->view->order = $order;
	}
	public function manageAction()
	{
		$searchRequest = new SearchRequest();
		$issue = new Issue();
		$filterData = $searchRequest->getAdapter()->fetchAll($searchRequest->select());
		
		$i = 0;
		foreach ($filterData as $data) {
			$sParams = $this->_processXml($data['reqcontent']);
			$where = $this->_buildWhere($sParams);
			$filterData[$i]['c'] = $issue->getIssuesCount($where);
			$i++;
		}
		
		$this->view->filterData = $filterData;
	}
	public function newAction()
	{
		$this->view->current = 'filter';
		$this->view->inc_jquery = true;
		$projectId = $this->_getParam('pid',1);
		
		$issue = new Issue();
		$project = new Project();
		$projectVersion = new ProjectVersion();
		$issueType = new IssueType();
		$component = new Component();
		$priority = new Priority();
		$issueStatus = new IssueStatus();
		$resolution = new Resolution();
		$issueTypeData = $issueType->getAdapter()->fetchAll($issueType->select());
		
		$projectsData = $project->getAdapter()->fetchAll($project->select());
		
		$projectVersionsData = $projectVersion->getAdapter()->fetchAll($projectVersion->select());
		
		$componentsData = $component->getAdapter()->fetchAll($component->select());
		
		$statusData = $issueStatus->getAdapter()->fetchAll($issueStatus->select());
		
		$prioritiesData = $priority->getAdapter()->fetchAll($priority->select());
		
		$resolutionsData = $resolution->getAdapter()->fetchAll($resolution->select());
		
		if ($this->getRequest()->isPost()) {
			$projects = $this->_getParam('projects');
			$issueType  = $this->_getParam('issuetype');
			$fixVersions = $this->_getParam('fixVersion');
			$components = $this->_getParam('component');
			$affectVersions = $this->_getParam('affectVersion');
			$reporter = $this->_getParam('reporter');
			if ($reporter == 'specify') {
				$reporterName = $this->_getParam('reporterName');
			}
			$assignee = $this->_getParam('assignee');
			if ($assignee == 'specify') {
				$assigneeName = $this->_getParam('assigneeName');
			}			
			$statuses = $this->_getParam('status');
			$resolutions = $this->_getParam('resolution');
			$priorities = $this->_getParam('priority');
			$createdAfter = $this->_getParam('createdAfter');
			$createdBefore = $this->_getParam('createdBefore');
			$createdPrevious = $this->_getParam('createdPrevious');
			$createdNext = $this->_getParam('createdNext');
			$updatedAfter = $this->_getParam('updatedAfter');
			$updatedBefore = $this->_getParam('updatedBefore');
			$updatedPrevious = $this->_getParam('updatedPrevious');
			$updatedNext = $this->_getParam('updatedNext');
			$duedateAfter = $this->_getParam('duedateAfter');
			$duedateBefore = $this->_getParam('duedateBefore');
			$duedatePrevious = $this->_getParam('duedatePrevious');
			$duedateNext = $this->_getParam('duedateNext');
			
			$query = $this->_getParam('query');
			if ($query) {
				$summary = $this->_getParam('summary');
				$comments = $this->_getParam('comments');
				$description = $this->_getParam('description');
				$environment = $this->_getParam('environment');
			}
			
			$params = array();
			if(isset($projects)) {
				foreach ($projects as $projectId) {
					$params['projects'][] = $projectId;
				}
			}
			if(isset($issueType)) {
				foreach ($issueType as $type) {
					$params['issuetypes'][] = $type;
				}
			}
			if ($reporter) {
				$params['reporter'] = $reporter;
				if ($reporter == 'specify' && isset($reporterName)) {
					$params['reporterName'] = $reporterName;
				}
			}
			if ($assignee) {
				$params['assignee'] = $assignee;
				if ($assignee == 'specify' && isset($assigneeName)) {
					$params['assigneeName'] = $assigneeName;
				}
			}
			if(isset($fixVersions)) {
				foreach ($fixVersions as $fixVersion) {
					$params['fixVersions'][] = $fixVersion;
				}
			}
			if(isset($components)) {
				foreach ($components as $componentD) {
					$params['components'][] = $componentD;
				}
			}
			if(isset($affectVersions)) {
				foreach ($affectVersions as $affectVersion) {
					$params['affectVersions'][] = $affectVersion;
				}
			}
			
			if(isset($query)) {
				$params['query']['text'] = $query;
				if ($summary) {
					$params['query']['summary'] = true;
				}
				if ($description) {
					$params['query']['description'] = true;
				}
				if ($comments) {
					$params['query']['comments'] = true;
				}
				if ($environment) {
					$params['query']['environment'] = true;
				}
			}
			if(isset($statuses)) {
				foreach ($statuses as $statusId) {
					$params['statuses'][] = $statusId;
				}
			}
			if(isset($resolutions)) {
				foreach ($resolutions as $resolutionId) {
					$params['resolutions'][] = $resolutionId;
				}
			}
			if(isset($priorities)) {
				foreach ($priorities as $priorityId) {
					$params['priorities'][] = $priorityId;
				}
			}
			
			if($createdAfter) {
				$params['createdAfter'] = $createdAfter;
			}
			if($createdBefore) {
				$params['createdBefore']= $createdBefore;
			}
		
			
			if($createdPrevious) {
				$createdPreviousDate = new DateTime();
				$createdPreviousDate->modify($createdPrevious);
				$params['createdPrevious'] =$createdPreviousDate;
			}
			
			if($createdNext) {
				$createdNextDate = new DateTime();
				$createdNextDate->modify($createdNext);
				$params['createdNext'] =$createdNextDate;
			}
			
			if($updatedAfter) {
				$params['updatedAfter'] = $createdAfter;
			}
			if($updatedBefore) {
				$params['updatedBefore'] = $createdBefore;
			}
			
			if($updatedPrevious) {
				$updatedPreviousDate = new DateTime();
				$updatedPreviousDate->modify($updatedPrevious);
				$params['updatedPrevious'] =$updatedPreviousDate;
			}
			
			if($updatedNext) {
				$updatedNextDate = new DateTime();
				$updatedNextDate->modify($updatedNext);
				$params['updatedNext'] =$updatedNextDate;
			}
		
			if($duedateAfter) {
				$params['duedateAfter'] = $duedateAfter;
			}
			if($duedateBefore) {
				$params['duedateBefore'] = $duedateBefore;
			}
			
			if($duedatePrevious) {
				$duedatePreviousDate = new DateTime();
				$duedatePreviousDate->modify($duedatePrevious);
				$params['duedatePrevious'] =$duedatePreviousDate;
			}
			
			if($duedateNext) {
				$duedateNextDate = new DateTime();
				$duedateNextDate->modify($duedateNext);
				$params['duedateNext'] =$duedateNextDate;
			}
			
			//Zend_Debug::dump($params);
			$where = $this->_buildWhere($params);
			$issuesData = $issue->getIssues($where);
			$xml = $this->_generateXml($params);
			/*header("Content-type:application/xml; charset=utf-8");
			echo $xml;exit;*/
			$Zend_Auth = new Zend_Session_Namespace('Zend_Auth');
			$Zend_Auth->filterXml = $xml;
			$this->view->issuesData = $issuesData;
		}
		$this->view->params = $params;
		$this->view->statusData = $statusData;
		$this->view->priorities = $prioritiesData;
		$this->view->resolutions = $resolutionsData;
		$this->view->projects = $projectsData;
		$this->view->fixVersionsData = $projectVersionsData;
		$this->view->affectVersionsData = $projectVersionsData;
		$this->view->componentsData = $componentsData;
		$this->view->issueTypeData = $issueTypeData;
	}
	
	public function editAction()
	{
		$this->view->current = 'filter';
		$this->view->inc_jquery = true;
		$searchRequest = new SearchRequest();
		$filterId = $this->_getParam('id');
		
		$project = new Project();
		$issue = new Issue();
		$issueType = new IssueType();
		$component = new Component();
		$priority = new Priority();
		$issueStatus = new IssueStatus();
		$resolution = new Resolution();
		$issueTypeData = $issueType->getAdapter()->fetchAll($issueType->select());
		
		$projectsData = $project->getAdapter()->fetchAll($project->select());
		
		$statusData = $issueStatus->getAdapter()->fetchAll($issueStatus->select());
		
		$prioritiesData = $priority->getAdapter()->fetchAll($priority->select());
		
		$resolutionsData = $resolution->getAdapter()->fetchAll($resolution->select());
		
		if ($this->getRequest()->isPost()) {
			
			$projects = $this->_getParam('projects');
			$issueType  = $this->_getParam('issuetype');
			$fixVersions = $this->_getParam('fixVersion');
			$components = $this->_getParam('component');
			$affectVersions = $this->_getParam('affectVersion');
			$reporter = $this->_getParam('reporter');
			if ($reporter == 'specify') {
				$reporterName = $this->_getParam('reporterName');
			}
			$assignee = $this->_getParam('assignee');
			if ($assignee == 'specify') {
				$assigneeName = $this->_getParam('assigneeName');
			}			
			$statuses = $this->_getParam('status');
			$resolutions = $this->_getParam('resolution');
			$priorities = $this->_getParam('priority');
			$createdAfter = $this->_getParam('createdAfter');
			$createdBefore = $this->_getParam('createdBefore');
			$createdPrevious = $this->_getParam('createdPrevious');
			$createdNext = $this->_getParam('createdNext');
			$updatedAfter = $this->_getParam('updatedAfter');
			$updatedBefore = $this->_getParam('updatedBefore');
			$updatedPrevious = $this->_getParam('updatedPrevious');
			$updatedNext = $this->_getParam('updatedNext');
			$duedateAfter = $this->_getParam('duedateAfter');
			$duedateBefore = $this->_getParam('duedateBefore');
			$duedatePrevious = $this->_getParam('duedatePrevious');
			$duedateNext = $this->_getParam('duedateNext');
			
			$query = $this->_getParam('query');
			if ($query) {
				$summary = $this->_getParam('summary');
				$comments = $this->_getParam('comments');
				$description = $this->_getParam('description');
				$environment = $this->_getParam('environment');
			}
			
			$params = array();
			if(isset($projects)) {
				foreach ($projects as $projectId) {
					$params['projects'][] = $projectId;
				}
			}
			if(isset($issueType)) {
				foreach ($issueType as $type) {
					$params['issuetypes'][] = $type;
				}
			}
			if ($reporter) {
				$params['reporter'] = $reporter;
				if ($reporter == 'specify' && isset($reporterName)) {
					$params['reporterName'] = $reporterName;
				}
			}
			if ($assignee) {
				$params['assignee'] = $assignee;
				if ($assignee == 'specify' && isset($assigneeName)) {
					$params['assigneeName'] = $assigneeName;
				}
			}
			if(isset($fixVersions)) {
				foreach ($fixVersions as $fixVersion) {
					$params['fixVersions'][] = $fixVersion;
				}
			}
			if(isset($components)) {
				foreach ($components as $componentD) {
					$params['components'][] = $componentD;
				}
			}
			if(isset($affectVersions)) {
				foreach ($affectVersions as $affectVersion) {
					$params['affectVersions'][] = $affectVersion;
				}
			}
			
			if(isset($query)) {
				$params['query']['text'] = $query;
				if ($summary) {
					$params['query']['summary'] = true;
				}
				if ($description) {
					$params['query']['description'] = true;
				}
				if ($comments) {
					$params['query']['comments'] = true;
				}
				if ($environment) {
					$params['query']['environment'] = true;
				}
			}
			if(isset($statuses)) {
				foreach ($statuses as $statusId) {
					$params['statuses'][] = $statusId;
				}
			}
			if(isset($resolutions)) {
				foreach ($resolutions as $resolutionId) {
					$params['resolutions'][] = $resolutionId;
				}
			}
			if(isset($priorities)) {
				foreach ($priorities as $priorityId) {
					$params['priorities'][] = $priorityId;
				}
			}
			
			if($createdAfter) {
				$params['createdAfter'] = $createdAfter;
			}
			if($createdBefore) {
				$params['createdBefore']= $createdBefore;
			}
		
			
			if($createdPrevious) {
				$createdPreviousDate = new DateTime();
				$createdPreviousDate->modify($createdPrevious);
				$params['createdPrevious'] =$createdPreviousDate;
			}
			
			if($createdNext) {
				$createdNextDate = new DateTime();
				$createdNextDate->modify($createdNext);
				$params['createdNext'] =$createdNextDate;
			}
			
			if($updatedAfter) {
				$params['updatedAfter'] = $createdAfter;
			}
			if($updatedBefore) {
				$params['updatedBefore'] = $createdBefore;
			}
			
			if($updatedPrevious) {
				$updatedPreviousDate = new DateTime();
				$updatedPreviousDate->modify($updatedPrevious);
				$params['updatedPrevious'] =$updatedPreviousDate;
			}
			
			if($updatedNext) {
				$updatedNextDate = new DateTime();
				$updatedNextDate->modify($updatedNext);
				$params['updatedNext'] =$updatedNextDate;
			}
		
			if($duedateAfter) {
				$params['duedateAfter'] = $duedateAfter;
			}
			if($duedateBefore) {
				$params['duedateBefore'] = $duedateBefore;
			}
			
			if($duedatePrevious) {
				$duedatePreviousDate = new DateTime();
				$duedatePreviousDate->modify($duedatePrevious);
				$params['duedatePrevious'] =$duedatePreviousDate;
			}
			
			if($duedateNext) {
				$duedateNextDate = new DateTime();
				$duedateNextDate->modify($duedateNext);
				$params['duedateNext'] =$duedateNextDate;
			}
			
			//Zend_Debug::dump($params);
			//$where = $this->_buildWhere($params);
			//$issuesData = $issue->getIssues($where);
			$xml = $this->_generateXml($params);
			//header("Content-type:application/xml; charset=utf-8");
			//echo $xml;exit;
			if ($filterId) {
				$searchRequest->update(array(
					'reqcontent' => $xml
				)," id = $filterId");
			}
		}
		
		$searchRequestData = $searchRequest->getAdapter()->fetchRow($searchRequest->select()->where('id=?',$filterId));
		// saving filter xml in session for future use- when save as is pressed.
		$Zend_Auth = new Zend_Session_Namespace('Zend_Auth');
		$Zend_Auth->filterXml = $searchRequestData['reqcontent'];
		
		$params = $this->_processXml($searchRequestData['reqcontent']);
		$where = $this->_buildWhere($params);
		$issuesData = $issue->getIssues($where);
		
		$this->view->issuesData = $issuesData;
		$this->view->filterData = $searchRequestData;
		$this->view->id = $filterId;
		$this->view->params = $params;
		$this->view->statusData = $statusData;
		$this->view->priorities = $prioritiesData;
		$this->view->resolutions = $resolutionsData;
		$this->view->projects = $projectsData;
		$this->view->issueTypeData = $issueTypeData;
	}
	
	public function saveAction()
	{
		$form = new AddFilterForm();
		$searchRequest = new SearchRequest();
		$Zend_Auth = new Zend_Session_Namespace('Zend_Auth');
		if ($this->getRequest()->isPost()) {
			$formData = $this->_request->getPost();
			if ($form->isValid($formData)) {
				$data = array(
					'filtername' => $formData['name'],
					'description' => $formData['description'],
					'authorname' => 'Faheem Abbas',
					'reqcontent' => $Zend_Auth->filterXml
				);
				$searchRequest->insert($data);
			}
			//Zend_Debug::dump($formData);exit;
			//header("Content-type:application/xml; charset=utf-8");
			//echo $xml;exit;
			
		}
		$this->view->form = $form;
	}
	
	protected function _buildWhere($params)
	{
		$where = "1=1";
		$i = 0;
		for($i = 0 ; $i < count($params['projects']); $i++) {
			if ($i == 0) {
				$where .= " AND (";
			}
			$where .= "project = ". $params['projects'][$i];
			if($params['projects'][$i+1]) {
				$where .= " OR ";
			} else {
				$where .= ')';
			}
		}
		
		$i = 0;
		for($i = 0 ; $i < count($params['issuetypes']); $i++) {
			if ($i == 0) {
				$where .= " AND (";
			}
			$where .= "issuetype = ". $params['issuetypes'][$i];
			if($params['issuetypes'][$i+1]) {
				$where .= " OR ";
			} else {
				$where .= ')';
			}
		}
		
		if($params['reporter']) {
			if($params['reporter'] == 'any') {
			
			} elseif ($params['reporter'] == 'no') {
				$where .= " AND issue.reporter = ''";
			} elseif ($params['reporter'] == 'current') {
				$auth = Zend_Auth::getInstance();
				if($auth->getIdentity()) {
					$userInfo = $auth->getStorage()->read();
					$where .= " AND issue.reporter = '".$userInfo->fullname."'";
				}
			} elseif ($params['reporter'] == 'specify' && isset($params['reporterName'])) {
				$where .= " AND issue.reporter = '".$params['reporterName']."'";
			}
		}
		
		if($params['assignee']) {
			if($params['assignee'] == 'any') {
			
			} elseif ($params['assignee'] == 'no') {
				$where .= " AND issue.assignee = ''";
			} elseif ($params['assignee'] == 'current') {
				$auth = Zend_Auth::getInstance();
				if($auth->getIdentity()) {
					$userInfo = $auth->getStorage()->read();
					$where .= " AND issue.assignee = '".$userInfo->fullname."'";
				}
			} elseif ($params['assignee'] == 'specify' && isset($params['assigneeName'])) {
				$where .= " AND issue.assignee = '".$params['assigneeName']."'";
			}
		}
		
		$i = 0;
		for($i = 0 ; $i < count($params['fixVersions']); $i++) {
			if ($i == 0) {
				$where .= " AND (";
			}
			$where .= "issue.id IN (SELECT source_node_id FROM nodeassociation where association_type ='IssueFixVersion' AND sink_node_id = ". $params['fixVersions'][$i].")";
			if($params['fixVersions'][$i+1]) {
				$where .= " OR ";
			} else {
				$where .= ')';
			}
		}
		
		
		$i = 0;
		for($i = 0 ; $i < count($params['components']); $i++) {
			if ($i == 0) {
				$where .= " AND (";
			}
			$where .= "issue.id IN (SELECT source_node_id FROM nodeassociation where association_type ='IssueComponent' AND sink_node_id = ". $params['components'][$i].")";
			if($params['components'][$i+1]) {
				$where .= " OR ";
			} else {
				$where .= ')';
			}
		}
		
		$i = 0;
		for($i = 0 ; $i < count($params['affectVersions']); $i++) {
			if ($i == 0) {
				$where .= " AND (";
			}
			$where .= "issue.id IN (SELECT source_node_id FROM nodeassociation where association_type ='IssueVersion' AND sink_node_id = ". $params['affectVersions'][$i].")";
			if($params['affectVersions'][$i+1]) {
				$where .= " OR ";
			} else {
				$where .= ')';
			}
		}
		
		
		//Zend_Debug::dump($params);
		if($params['query']['text'] != '') {
			$flag = false;
			$where .= " AND (";
			if($params['query']['summary']) {
				$where .= "summary like '%". $params['query']['text']."%'";
				$flag = true;
			}
			if($params['query']['description']) {
				if($flag) {
					$where .= " OR ";
				}
				$where .= "issue.description like '%". $params['query']['text']."%'";
				$flag = true;
			}
			if($params['query']['comments']) {
				if($flag) {
					$where .= " OR ";
				}
				$where .= "issue.id IN (SELECT issueid from action where action_type = 'comment' AND action_body like '%".$params['query']['text']."%')";
				$flag = true;
			}
			/*if($params['query']['description']) {
				if($flag) {
					$where .= " OR ";
				}
				$where .= "description =". $params['query']['description'];
				$flag = true;
			}*/
			if ($flag == false) {
				$where .= "summary like '%". $params['query']['text']."%'";
				$where .= " OR issue.description like '%". $params['query']['text']."%'";
				$where .= " OR issue.id IN (SELECT issueid from action where action_type = 'comment' AND action_body like '%".$params['query']['text']."%')";
				//$where .= "summary =". $params['query']['summary'];
				//$where .= "summary =". $params['query']['summary'];
			}
			$where .= ")";
		}
		
		$i = 0;
		for($i = 0 ; $i < count($params['statuses']); $i++) {
			if ($i == 0) {
				$where .= " AND (";
			}
			$where .= "issuestatus = ". $params['statuses'][$i];
			if($params['statuses'][$i+1]) {
				$where .= " OR ";
			} else {
				$where .= ')';
			}
		}
		
		$i = 0;
		for($i = 0 ; $i < count($params['resolutions']); $i++) {
			if ($i == 0) {
				$where .= " AND (";
			}
			$where .= "resolution = ". $params['resolutions'][$i];
			if($params['resolutions'][$i+1]) {
				$where .= " OR ";
			} else {
				$where .= ')';
			}
		}
		
		$i = 0;
		for($i = 0 ; $i < count($params['priorities']); $i++) {
			if ($i == 0) {
				$where .= " AND (";
			}
			$where .= "priority = ". $params['priorities'][$i];
			if($params['priorities'][$i+1]) {
				$where .= " OR ";
			} else {
				$where .= ')';
			}
		}
		
		if ($params['createdAfter']) {
			$where .= " AND created > '".date('Y-m-d',strtotime($params['createdAfter']))."'";
		}
		
		if ($params['createdBefore']) {
			$where .= " AND created < '".date('Y-m-d',strtotime($params['createdBefore']))."'";
		}
		
		if ($params['createdPrevious']) {
			//$where .= "";
		}
		if($params['createdNext']) {
		
		}
		
		if ($params['updatedAfter']) {
			$where .= " AND updated > '".date('Y-m-d',strtotime($params['updatedAfter']))."'";
		}
		
		if ($params['updatedBefore']) {
			$where .= " AND updated < '".date('Y-m-d',strtotime($params['updatedBefore']))."'";
		}
		
		if ($params['updatedPrevious']) {
			//$where .= "";
		}
		if($params['updatedNext']) {
		
		}
		
		if ($params['duedateAfter']) {
			$where .= " AND duedate > '".date('Y-m-d',strtotime($params['duedateAfter']))."'";
		}
		
		if ($params['duedateBefore']) {
			$where .= " AND duedate < '".date('Y-m-d',strtotime($params['duedateBefore']))."'";
		}
		
		if ($params['resolvedAfter']) {
			$where .= " AND (issue.issuestatus IN (SELECT id FROM issuestatus WHERE pname = 'Closed' OR pname = 'Resolved'))";
			$date = new Zend_Date();
			$date->sub(1, Zend_Date::WEEK);
			$today = $date->get();
			$where .= " And issue.updated >= '".date('Y-m-d',$today)."'";
		}
		
		if ($params['resolvedBefore']) {
			$where .= " AND (issue.issuestatus IN (SELECT id FROM issuestatus WHERE pname = 'Closed' OR pname = 'Resolved'))";
			$date = new Zend_Date();
			$date->sub(1, Zend_Date::WEEK);
			$today = $date->get();
			$where .= " And issue.updated < '".date('Y-m-d',$today)."'";
		}
		if($params['fixfor'] == '-1w') {
			$where .=' And (issue.id NOT IN (SELECT source_node_id from nodeassociation
												where association_type = "IssueFixVersion"))';
		}
		
		if ($params['duedatePrevious']) {
			//$where .= "";
		}
		if($params['duedateNext']) {
		
		}
		//echo $where;exit;
		return $where;
	}
	
	protected function _generateXml($params)
	{
		$xmlDoc = new DOMDocument('1.0', 'utf-8');
		$xmlDoc->formatOutput = true;
		$root = $xmlDoc->createElement('root');
		$root = $xmlDoc->appendChild($root);
		
		$projects = $params['projects'];
		$issueType  = $params['issuetypes'];
		$statuses = $params['statuses'];
		$resolutions = $params['resolution'];
		$priorities = $params['priority'];
		$createdAfter = $params['createdAfter'];
		$createdBefore = $params['createdBefore'];
		$updatedAfter = $params['updatedAfter'];
		$updatedBefore = $params['updatedBefore'];
		$duedateAfter = $params['duedateAfter'];
		$duedateBefore = $params['duedateBefore'];
		$resolvedAfter = $params['resolvedAfter'];
		$resolvedBefore = $params['resolvedBefore'];
		
		$query = $params['query'];
			if ($query) {
				$summary = $params['query']['summary'];
				$comments = $params['query']['comments'];
				$description = $params['query']['description'];
				$environment = $params['query']['environment'];
			}
			
		$reporter = $params['reporter'];
		
		if ($reporter == 'specify') {
				$reporterName = $this->_getParam('reporterName');
		}
		
		$assignee = $params['assignee'];
		if ($assignee == 'specify') {
			$assigneeName = $this->_getParam('assigneeName');
		}
		
		if(isset($projects)) {
			$projectNode = $xmlDoc->createElement('projects');
			$projectNode = $root->appendChild($projectNode);
			foreach ($projects as $projectId) {
				$project = $xmlDoc->createElement('project');
				$project = $projectNode->appendChild($project);
				$project->setAttribute('id', $projectId);
				//$text = $xmlDoc->createTextNode($projectId);
				//$project = $project->appendChild($text);
			}
		}
		if(isset($issueType)) {
			$typeNode = $xmlDoc->createElement('issuetypes');
			$typeNode = $root->appendChild($typeNode);
			foreach ($issueType as $type) {
				$issueType = $xmlDoc->createElement('issuetype');
				$issueType = $typeNode->appendChild($issueType);
				$issueType->setAttribute('value', $type);
			}
		}
		
		if ($query) {
				$queryNode = $xmlDoc->createElement('query');
				$queryNode = $root->appendChild($queryNode);
				$text = $xmlDoc->createTextNode($query['text']);
				$queryNodeText = $queryNode->appendChild($text);
				
				if ($summary) {
					$queryNode->setAttribute('summary', true);
				}
				
				if($description) {
					$queryNode->setAttribute('description', true);
				}
				if($comments) {
					$queryNode->setAttribute('comments', true);
				}
				if($environment) {
					$queryNode->setAttribute('environment', true);
				}
				
			}
		
		if($reporter) {
			$reporterNode = $xmlDoc->createElement('reporter');
			$reporterNode = $root->appendChild($reporterNode);
			$reporterNode->setAttribute('key',$reporter);
			if($reporter == 'any') {
			
			} elseif ($reporter == 'no') {
				//$where .= " AND issue.reporter = ''";
				$text = $xmlDoc->createTextNode('');
				$reporterNodeText = $reporterNode->appendChild($text);
			} elseif ($reporter == 'current') {
				$auth = Zend_Auth::getInstance();
				if($auth->getIdentity()) {
					$userInfo = $auth->getStorage()->read();
					//$where .= " AND issue.reporter = '".$userInfo->fullname."'";
					$text = $xmlDoc->createTextNode($userInfo->fullname);
					$reporterNodeText = $reporterNode->appendChild($text);
				}
			} elseif ($reporter == 'specify' && isset($reporterName)) {
				//$where .= " AND issue.reporter = '".$reporterName."'";
				$text = $xmlDoc->createTextNode($reporterName);
					$reporterNodeText = $reporterNode->appendChild($text);
			}
		}
		
		if($assignee) {
			$assigneeNode = $xmlDoc->createElement('assignee');
			$assigneeNode = $root->appendChild($assigneeNode);
			$assigneeNode->setAttribute('key',$assignee);
			if($assignee == 'any') {
			
			} elseif ($assignee == 'no') {
				$text = $xmlDoc->createTextNode('');
				$assigneeNodeText = $assigneeNode->appendChild($text);
				//$where .= " AND issue.assignee = ''";
			} elseif ($assignee == 'current') {
				$auth = Zend_Auth::getInstance();
				if($auth->getIdentity()) {
					$userInfo = $auth->getStorage()->read();
					$text = $xmlDoc->createTextNode($userInfo->fullname);
					$assigneeNodeText = $assigneeNode->appendChild($text);
					//$where .= " AND issue.assignee = '".$userInfo->fullname."'";
				}
			} elseif ($assignee == 'specify' && isset($assigneeName)) {
				$text = $xmlDoc->createTextNode($assigneeName);
				$assigneeNodeText = $assigneeNode->appendChild($text);
				//$where .= " AND issue.assignee = '".$assigneeName."'";
			}
		}
		
		if(isset($statuses)) {
			$statusNode = $xmlDoc->createElement('issuestatuses');
			$statusNode = $root->appendChild($statusNode);
			foreach ($statuses as $statusId) {
				$status = $xmlDoc->createElement('issuestatus');
				$status = $statusNode->appendChild($status);
				$status->setAttribute('value', $statusId);
			}
		}
		if(isset($resolutions)) {
			$resolutionNode = $xmlDoc->createElement('resolutions');
			$resolutionNode = $root->appendChild($resolutionNode);
			foreach ($resolutions as $resolutionId) {
				$resolution = $xmlDoc->createElement('resolution');
				$resolution = $resolutionNode->appendChild($resolution);
				$resolution->setAttribute('value', $resolutionId);
			}
		}
		if(isset($priorities)) {
			$priorityNode = $xmlDoc->createElement('priorities');
			$priorityNode = $root->appendChild($priorityNode);
			foreach ($priorities as $priorityId) {
				$priority = $xmlDoc->createElement('priority');
				$priority = $priorityNode->appendChild($priority);
				$priority->setAttribute('value', $priorityId);
			}
		}
		if ($createdAfter || $createdBefore) {
			$created = $xmlDoc->createElement('created');
			$created = $root->appendChild($created);
			if($createdAfter) {
				$created->setAttribute('after', $createdAfter);
			}
			if($createdBefore) {
				$created->setAttribute('before', $createdBefore);
			}
		}
		if ($updatedAfter || $updatedBefore) {
			$updated = $xmlDoc->createElement('updated');
			$updated = $root->appendChild($updated);
			if($updatedAfter) {
				$updated->setAttribute('after', $updatedAfter);
			}
			if($updatedBefore) {
				$updated->setAttribute('before', $updatedBefore);
			}
		}
		if ($duedateAfter || $duedateBefore) {
			$duedate = $xmlDoc->createElement('duedate');
			$duedate = $root->appendChild($duedate);
			if($duedateAfter) {
				$duedate->setAttribute('after', $duedateAfter);
			}
			if($duedateBefore) {
				$duedate->setAttribute('before', $duedateBefore);
			}
		}
		
		if ($resolvedAfter || $resovedBefore) {
			$resolved = $xmlDoc->createElement('resolved');
			$resolved = $root->appendChild($resolved);
			if($resolvedAfter) {
				$duedate->setAttribute('after', $resolvedAfter);
			}
			if($resolvedBefore) {
				$duedate->setAttribute('before', $resolvedBefore);
			}
		}
		
		//header("Content-type:application/xml; charset=utf-8");
		$xml = $xmlDoc->saveXML();
		//exit;
		return $xml;
		
	}
	
	protected function _processXml($data)
	{
		$objReader = XMLReader::XML($data);
			$params = array();
				while ($objReader->read()) {
					if($objReader->nodeType == 1 && $objReader->localName == 'project' && $objReader->hasAttributes) {
						$params['projects'][] = $objReader->getAttribute('id');
					}
					if($objReader->nodeType == 1 && $objReader->localName == 'issuetype' && $objReader->hasAttributes) {
						$params['issuetypes'][] = $objReader->getAttribute('value');
					}
					if($objReader->nodeType == 1 && $objReader->localName == 'query') {
						$query = $objReader->readString();
						$params['query']['text'] = $query;
						if($objReader->getAttribute['summary']) {
							$params['query']['summary'] = true;
						}
						if($objReader->getAttribute['description']) {
							$params['query']['description'] = true;
						}
						if($objReader->getAttribute['comments']) {
							$params['query']['comments'] = true;
						}
						if($objReader->getAttribute['environment']) {
							$params['query']['environment'] = true;
						}
					}
					
					if($objReader->nodeType == 1 && $objReader->localName == 'reporter' && $objReader->hasAttributes) {
						$params['reporter'] = $objReader->getAttribute('key');
						if ($params['reporter'] == 'specify') {
							$params['reporterName'] = $objReader->readString();
						}
					
					}
					if($objReader->nodeType == 1 && $objReader->localName == 'assignee' && $objReader->hasAttributes) {
						$params['assignee'] = $objReader->getAttribute('key');
						if ($params['assignee'] == 'specify') {
							$params['assigneeName'] = $objReader->readString();
						}
					
					}
					
					if($objReader->nodeType == 1 && $objReader->localName == 'issuestatus' && $objReader->hasAttributes) {
						$params['statuses'][] = $objReader->getAttribute('value');
					}
					if($objReader->nodeType == 1 && $objReader->localName == 'resolution' && $objReader->hasAttributes) {
						$params['resolutions'][] = $objReader->getAttribute('value');
					}
					if($objReader->nodeType == 1 && $objReader->localName == 'priority' && $objReader->hasAttributes) {
						$params['priorities'][] = $objReader->getAttribute('value');
					}
					if($objReader->nodeType == 1 && $objReader->localName == 'created' && $objReader->hasAttributes) {
						if ($objReader->getAttribute('after')) {
							$params['createdAfter'] = $objReader->getAttribute('after');
						}
						if ($objReader->getAttribute('before')) {
							$params['createdBefore'] = $objReader->getAttribute('before');
						}
					}
					if($objReader->nodeType == 1 && $objReader->localName == 'updated' && $objReader->hasAttributes) {
						if ($objReader->getAttribute('after')) {
							$params['updatedAfter'] = $objReader->getAttribute('after');
						}
						if ($objReader->getAttribute('before')) {
							$params['updatedBefore'] = $objReader->getAttribute('before');
						}
					}
					if($objReader->nodeType == 1 && $objReader->localName == 'duedate' && $objReader->hasAttributes) {
						if ($objReader->getAttribute('after')) {
							$params['duedateAfter'] = $objReader->getAttribute('after');
						}
						if ($objReader->getAttribute('before')) {
							$params['duedateBefore'] = $objReader->getAttribute('before');
						}
					}
					
					if($objReader->nodeType == 1 && $objReader->localName == 'resolved' && $objReader->hasAttributes) {
						if ($objReader->getAttribute('after')) {
							$params['resolvedAfter'] = $objReader->getAttribute('after');
						}
						if ($objReader->getAttribute('before')) {
							$params['resolvedBefore'] = $objReader->getAttribute('before');
						}
					}
					
					if($objReader->nodeType == 1 && $objReader->localName == 'fixfor' && $objReader->hasAttributes) {
						if ($objReader->getAttribute('value')) {
							$params['fixfor'] = $objReader->getAttribute('value');
						}
					}
			}
		return $params;
	}
	
	protected function _getField($field)
	{
		if ($field == 0) {
			$field = "issueTypeName";
		}
		if ($field == 1) {
			$field = "pkey";
		}
		if ($field == 2) {
			$field = "summary";
		}
		if ($field == 3) {
			$field = "assignee";
		}
		if ($field == 4) {
			$field = "reporter";
		}
		if ($field == 5) {
			$field = "priorityName";
		}
		if ($field == 6) {
			$field = "issueStatusName";
		}
		if ($field == 7) {
			$field = "resolutionName";
		}
		if ($field == 8) {
			$field = "created";
		}
		if ($field == 9) {
			$field = "updated";
		}
		if ($field == 10) {
			$field = "duedate";
		}
		return $field;
	}

}